/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Form, Divider, Select, message, Row, Col } from 'antd';
import KbModal from '@/components/KbModal';
import { connect } from "dva";

const { Option } = Select
const FormItem = Form.Item;

@connect(({ loading, payment, clientManage }) => ({
  payment,
  clientManage,
  getList: loading.effects['clientManage/getClientManageList'],
}))
@Form.create()
export default class Modal extends Component {
  state = {
    loading: false,
    waybill_no: '',
    collection_amount: '',
    id: '',
    company_name: undefined,
    customer_name: "",
    customer_phone: "",
    remark: "",
    count: "1",
    customerId: '',
    newClientInfo: {},   ////新添加的客户信息，用于渲染modal框
    isNewAdd: false,  //是否是新增
  }

  componentDidMount() {
    const { dispatch } = this.props
    dispatch({  //获取客户信息，核销的下拉框数据
      type: 'clientManage/getClientManageList',
      payload: {
        search: '',
        kdySearch: '',
        page: 1,
      }
    })
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.record) {
      const { company_name, customer_name, customer_phone, remark, waybill_no, count, group_waybill_no, group_id, collection_amount } = nextProps.record[0] || nextProps.record
      const isBatch = nextProps.record.length > 0

      if( customer_name !== this.state.customer_name ){
        this.setState({
          company_name,
          customer_name,
          customer_phone,
          remark,
          count: count || 1,
          customerId: ''  //清空customerId，避免当有客户名称时，模态框展示之前的数据
        })
      }

      if (group_waybill_no || group_id) {   //是否来自未回款统计页面
        this.setState({
          waybill_no: group_waybill_no,
          id: group_id,
          collection_amount,
          count
        })
        return
      }

      if (isBatch) {  //是否是批量核销
        let waybill_no = nextProps.record.map(item => item.waybill_no).join(',')
        let id = nextProps.record.map(item => item.id).join(',')
        let collection_amount = nextProps.record.map(item => item.collection_amount).reduce((prev, current) => (prev * 1 + current * 1).toFixed(2))
        let { company_name, customer_name, customer_phone, remark } = nextProps.record[0]

        this.setState({ 
          waybill_no,
          collection_amount,
          id,
          company_name,
          customer_name,
          customer_phone,
          remark,
          count: nextProps.record.length,
        })
      } else {
        this.setState({
          waybill_no,
          id: nextProps.record.id,
          collection_amount
        })
      }
    }
  }

  onOk = () => {
    const { hideModal, form, dispatch, searchVale, cleanSelectedKeys, type } = this.props
    const { company_name, customerId, customer_name, customer_phone, remark, isNewAdd } = this.state
    if (!customer_name) {
      message.error("请选择公司名称！")
      return
    }
    this.setState({ loading: true })

    form.validateFields((err, fieldsValue) => {
      if (err) return
      if (isNewAdd) { //新增公司需要的字段
        fieldsValue.customerId = customerId
        fieldsValue.companyName = company_name
        fieldsValue.customerName = customer_name
        fieldsValue.customerPhone = customer_phone
        fieldsValue.remark = remark
        fieldsValue.type = 'add'
      }

      dispatch({
        type: "payment/verifycatCollection",
        payload: {
          ...fieldsValue
        }
      }).then(() => {
        dispatch({
          type: type == 'check' ? 'payment/getCollectionPaymentList' : 'payment/getNoPayBackList',
          payload: {
            ...searchVale
          }
        })
        this.setState({ loading: false, customerId: "" },function(){
          cleanSelectedKeys && cleanSelectedKeys()          
          hideModal()
        })
      }).catch(() => {
        this.setState({ loading: false, customerId: "" })
      })
    })
  }

  onSelect = (value, option) => {
    this.setState({
      company_name: value,
      customerId: option.key,
      isNewAdd: true
    }) 
  }

  componentWillUpdate( nextProps, nextState ){
    if( nextProps.record ){
      const { clientManage: {clientManageList}, record } = nextProps
      const { customer_name, count } = record[0] || record
      const { customerId } = nextState
      const batch = nextProps.record.length

      if(customer_name == nextState.customer_name){
        clientManageList.list.map(item=>{
          if( item.id == customerId ){
            this.setState({
              company_name: item.customer,
              customer_name: item.linkman_name ,
              customer_phone: item.linkman_mobile,
              remark: item.remark,
              count: count || batch || 1,
            })
          }
        })
      }

    }
  }

  render() {
    const {
      loading,
      waybill_no,
      collection_amount,
      id,
      company_name,
      customer_name,
      customer_phone,
      remark,
      count,
    } = this.state
    const {
      record,
      hideModal,
      visible,
      title,
      type,
      form: { getFieldDecorator },
      clientManage: { clientManageList },
      ...restProps
    } = this.props

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    return (
      <KbModal
        loading={loading}
        destroyOnClose={true}
        cancelText={type !== "client" && "取消"}
        title={title}
        visible={visible}
        onCancel={hideModal}
        onOk={this.onOk}
        okText={type !== "client" && "确定"}
        title={type !== 'client' ? "核销（标记回款）" : "客户信息"}
        width={600}
        {...restProps}
      >
        {
          <Form  {...formItemLayout} >
            {
              type == 'client' ? null : <h3>客户信息</h3>
            }
            {
              (!customer_name && type !== 'client') ? (
                <Row type="flex" justify="start" align="middle">
                  <Col span={8}>
                    <Row type="flex" justify="space-between">
                      <Col>公司名称</Col>
                      <Col span={3}>:</Col>
                    </Row>
                  </Col>
                  <Col span={16}>
                    <FormItem style={{ marginBottom: 0 }}>
                      {
                        getFieldDecorator("companyName", {
                          initialValue: company_name
                        })(
                          <Select
                            onSelect={this.onSelect}
                            placeholder="请输入企业客户名称"
                            showSearch={true}
                          >
                            {
                              clientManageList.list.map(item => {
                                return (
                                  <Option key={item.id} value={item.customer} >{item.customer}</Option>
                                )
                              })
                            }
                          </Select>
                        )
                      }
                    </FormItem>
                  </Col>
                </Row>
              ) : (
                  <div>
                    <Row type="flex" justify="start" align="middle">
                      <Col span={8}>
                        <Row type="flex" justify="space-between">
                          <Col>公司名称</Col>
                          <Col span={3}>:</Col>
                        </Row>
                      </Col>
                      <Col span={16}>
                        <FormItem style={{ marginBottom: 0 }}>
                          <span>{company_name || "暂无"}</span>
                        </FormItem>
                      </Col>
                    </Row>
                    <Row type="flex" justify="start" align="middle">
                      <Col span={8}>
                        <Row type="flex" justify="space-between">
                          <Col>联系人</Col>
                          <Col span={3}>:</Col>
                        </Row>
                      </Col>
                      <Col span={16}>
                        <FormItem style={{ marginBottom: 0 }}>
                          <span>{customer_name || "暂无"}</span>
                        </FormItem>
                      </Col>
                    </Row>
                    <Row type="flex" justify="start" align="middle">
                      <Col span={8}>
                        <Row type="flex" justify="space-between">
                          <Col>联系人电话</Col>
                          <Col span={3}>:</Col>
                        </Row>
                      </Col>
                      <Col span={16}>
                        <FormItem style={{ marginBottom: 0 }}>
                          <span>{customer_phone || "暂无"}</span>
                        </FormItem>
                      </Col>
                    </Row>
                    <Row type="flex" justify="start" align="middle">
                      <Col span={8}>
                        <Row type="flex" justify="space-between">
                          <Col>回款信息</Col>
                          <Col span={3}>:</Col>
                        </Row>
                      </Col>
                      <Col span={16}>
                        <FormItem style={{ marginBottom: 0 }}>
                          <span>{remark || "暂无"}</span>
                        </FormItem>
                      </Col>
                    </Row>
                  </div>
                )
            }
            {
              type !== 'client' ? (
                <>
                  <Divider />
                  <h3>代收货款</h3>
                  <Row type="flex" justify="start" align="middle">
                    <Col span={8}>
                      <Row type="flex" justify="space-between">
                        <Col>订单总数</Col>
                        <Col span={3}>:</Col>
                      </Row>
                    </Col>
                    <Col span={16}>
                      <FormItem style={{ marginBottom: 0 }}>
                        <span>{count} 单</span>
                      </FormItem>
                    </Col>
                  </Row>
                  <Row type="flex" justify="start" align="middle">
                    <Col span={8}>
                      <Row type="flex" justify="space-between">
                        <Col>运单号</Col>
                        <Col span={3}>:</Col>
                      </Row>
                    </Col>
                    <Col span={16}>
                      <FormItem style={{ marginBottom: 0 }}>
                        {
                          getFieldDecorator('id', {
                            initialValue: id
                          })(
                            <span>{waybill_no}</span>
                          )
                        }
                      </FormItem>
                    </Col>
                  </Row>
                  <Row type="flex" justify="start" align="middle">
                    <Col span={8}>
                      <Row type="flex" justify="space-between">
                        <Col>代收货款总金额</Col>
                        <Col span={3}>:</Col>
                      </Row>
                    </Col>
                    <Col span={16}>
                      <FormItem style={{ marginBottom: 0 }}>
                        <span>{collection_amount} 元</span>
                      </FormItem>
                    </Col>
                  </Row>
                </>
              ) : null
            }
          </Form>
        }
      </KbModal>
    )
  }
}

Modal.propTypes = {
  visible: PropTypes.bool,
  wrappedComponentRef: PropTypes.func,
  onOk: PropTypes.func,
  okText: PropTypes.string,
  title: PropTypes.string,
  onCancel: PropTypes.func,
  status: PropTypes.number,
  changeActiveKey: PropTypes.func,
  record: PropTypes.any
}
